//
//  ProjectBrowser.m
//  iXNAT
//
//  Created by Daniel Blezek on 3/11/10.
//  Copyright 2010 __MyCompanyName__. All rights reserved.
//

#import "ProjectBrowser.h"
#import "JSON.h"
#import "ASIHTTPRequest.h"
#import "ProjectData.h"
#import "Utilities.h"

@implementation ProjectBrowser

/*
- (id)initWithStyle:(UITableViewStyle)style {
    // Override initWithStyle: if you create the controller programmatically and want to perform customization that is not appropriate for viewDidLoad.
    if (self = [super initWithStyle:style]) {
    }
    return self;
}
*/

- (void)loadProjects
{
  if ( dataLoaded ) {
    return;
  }
  NSString *urlString = @"http://central.xnat.org/REST/projects?format=json&columns=ID,URI,name,default";

  NSURL *url = [NSURL URLWithString:urlString];
  ASIHTTPRequest *request = [ASIHTTPRequest requestWithURL:url];
  [request setUsername:@"blezek"];
  [request setPassword:@"throwaway"];
  [request setDelegate:self];
  [activityView startAnimating];
  [request startAsynchronous];
}

- (void)requestFailed:(ASIHTTPRequest *)request
{
  NSError *error = [request error];
  NSString *message = [NSString stringWithFormat:@"Failed to get data %@", [error localizedDescription]];
  UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Failed" message:message delegate:nil cancelButtonTitle:@"Aw shucks" otherButtonTitles:nil];
  [activityView stopAnimating];
  [alert show];
  [alert release];
}

- (void)requestFinished:(ASIHTTPRequest *)request
{
  // Use when fetching text data
  NSString *jsonString = [request responseString];
	NSDictionary *json = [jsonString JSONValue];
	
  [projects removeAllObjects];
  
	// Now we need to dig through the resulting objects.
	// Read the documentation and make liberal use of the debugger or logs.
	NSArray *results = [[json objectForKey:@"ResultSet"] objectForKey:@"Result"];
	for (NSDictionary *result in results) {
    ProjectData *project = [[ProjectData alloc] init];
    project.projectID = [result objectForKey:@"ID"];
    project.uri = [result objectForKey:@"URI"];
    project.name = [result objectForKey:@"name"];
    project.description = [result objectForKey:@"description"];
    [projects addObject:project];
	}    
  [activityView stopAnimating];
  dataLoaded = YES;
  [self.tableView reloadData];
}


- (void)viewDidLoad {
  [super viewDidLoad];
  dataLoaded = NO;
  projects = [[NSMutableArray alloc] init];
  activityView = [[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleWhiteLarge];
  [self.navigationController.view addSubview:activityView];
  [self.navigationController.view bringSubviewToFront:activityView];
  [Utilities setActivityFrameLocation:activityView withParent:self.navigationController.view withAnimation:NO];
  self.navigationItem.rightBarButtonItem = [[[UIBarButtonItem alloc]
                                             initWithTitle:@"Reload"
                                             style:UIBarButtonItemStylePlain
                                             target:self
                                             action:@selector(reloadClicked:)] autorelease];
  
}



- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
}


- (void)viewDidAppear:(BOOL)animated {
  [super viewDidAppear:animated];
  [self loadProjects];

}
/*
- (void)viewWillDisappear:(BOOL)animated {
	[super viewWillDisappear:animated];
}
*/
/*
- (void)viewDidDisappear:(BOOL)animated {
	[super viewDidDisappear:animated];
}
*/


- (void)didReceiveMemoryWarning {
	// Releases the view if it doesn't have a superview.
    [super didReceiveMemoryWarning];
	
	// Release any cached data, images, etc that aren't in use.
}

- (void)viewDidUnload {
	// Release any retained subviews of the main view.
	// e.g. self.myOutlet = nil;
}


#pragma mark Table view methods

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 1;
}


// Customize the number of rows in the table view.
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return [projects count];
}


// Customize the appearance of table view cells.
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
  ProjectData *project = [projects objectAtIndex:indexPath.row];
  static NSString *CellIdentifier = @"Cell";
    
  UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
  if (cell == nil) {
    cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:CellIdentifier] autorelease];
  }
	cell.textLabel.text = project.name;
  cell.detailTextLabel.text = project.projectID;
  cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
  return cell;
}


- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    // Navigation logic may go here. Create and push another view controller.
	// AnotherViewController *anotherViewController = [[AnotherViewController alloc] initWithNibName:@"AnotherView" bundle:nil];
	// [self.navigationController pushViewController:anotherViewController];
	// [anotherViewController release];
}


/*
// Override to support conditional editing of the table view.
- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath {
    // Return NO if you do not want the specified item to be editable.
    return YES;
}
*/


/*
// Override to support editing the table view.
- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {
    
    if (editingStyle == UITableViewCellEditingStyleDelete) {
        // Delete the row from the data source
        [tableView deleteRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:YES];
    }   
    else if (editingStyle == UITableViewCellEditingStyleInsert) {
        // Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view
    }   
}
*/


/*
// Override to support rearranging the table view.
- (void)tableView:(UITableView *)tableView moveRowAtIndexPath:(NSIndexPath *)fromIndexPath toIndexPath:(NSIndexPath *)toIndexPath {
}
*/


/*
// Override to support conditional rearranging of the table view.
- (BOOL)tableView:(UITableView *)tableView canMoveRowAtIndexPath:(NSIndexPath *)indexPath {
    // Return NO if you do not want the item to be re-orderable.
    return YES;
}
*/


- (void)dealloc {
  [projects release];
  [super dealloc];
}

#pragma mark -
#pragma mark Button clicks
- (void)reloadClicked:(id) sender {
  dataLoaded = NO;
  [self loadProjects];
}

@end

